package com.jiaoyou.baojian.activity;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jiaoyou.baojian.BaojianApplication;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.adapter.RankAdapter;
import com.jiaoyou.baojian.adapter.UserDetailGiftAdapter;
import com.jiaoyou.baojian.dialog.SendGiftsDialog;
import com.jiaoyou.baojian.dialog.YesOrNoDialog;
import com.jiaoyou.baojian.entity.GiftEntity;
import com.jiaoyou.baojian.entity.GiveGiftListItem;
import com.jiaoyou.baojian.entity.UserDetail;
import com.jiaoyou.baojian.entity.UserInfo;
import com.jiaoyou.baojian.entity.response.RoomItemResponse;
import com.jiaoyou.baojian.entity.response.RoomListResponse;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.utils.ACache;
import com.jiaoyou.baojian.utils.GlideImageLoader;
import com.jiaoyou.baojian.utils.Utils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

public class UserInfoActivity extends BaseActivity {

    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.username)
    TextView username;
    @BindView(R.id.desc)
    TextView desc;
    @BindView(R.id.gift)
    TextView gift;
    @BindView(R.id.dianhua)
    TextView dianhua;
    @BindView(R.id.guanzhu)
    TextView guanzhu;
    @BindView(R.id.sound)
    TextView sound;
    @BindView(R.id.expand)
    ImageView expand;
    @BindView(R.id.follow)
    TextView follow;
    @BindView(R.id.followLayout)
    LinearLayout followLayout;
    @BindView(R.id.follower)
    TextView follower;
    @BindView(R.id.followerLayout)
    LinearLayout followerLayout;
    @BindView(R.id.attractiveness)
    TextView attractiveness;
    @BindView(R.id.attraTxt)
    TextView attraTxt;
    @BindView(R.id.arrtractivenessLayout)
    LinearLayout arrtractivenessLayout;
    @BindView(R.id.mygifts)
    RecyclerView mygifts;
    @BindView(R.id.myshouhu)
    RecyclerView myshouhu;
    @BindView(R.id.expandable_content)
    LinearLayout expandableContent;
    @BindView(R.id.gifts_layout)
    LinearLayout gifts_layout;
    @BindView(R.id.shouhu_layout)
    LinearLayout shouhu_layout;

    private UserInfo userInfo;
    private UserDetail userDetail;
    private MediaPlayer player;
    private Thread playThread;

    public static void start(Context context, int userid){
        if(!Utils.isLogin()){
            Intent intent = new Intent(context, LoginRegActivity.class);
            context.startActivity(intent);
            return;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.userId = userid;
        Intent intent = new Intent(context, UserInfoActivity.class);
        intent.putExtra("userinfo", userInfo);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        userInfo = (UserInfo) getIntent().getSerializableExtra("userinfo");

        if(userInfo != null && !TextUtils.isEmpty(userInfo.birthday))
            setTitle(userInfo.nickname + "，" + Utils.getAge(userInfo.birthday));
        else
            setTitle(userInfo.nickname);

        ButterKnife.bind(this);

        getData();

        waiting("获取用户信息...");
    }

    public void getData() {
        Api.getInstance().getUserDetail(userInfo.userId, new BaofangCallback<UserDetail>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                stopWaiting();
                toast("网络错误，请重试");
                finish();
            }

            @Override
            public void onSuccess(UserDetail userDetail) {
                stopWaiting();
                UserInfoActivity.this.userDetail = userDetail;
                if(userDetail.userInfo.userId == getLoginResponse().userInfo.userId){
                    getLoginResponse().update(UserInfoActivity.this, userDetail);
                }
                fillData();
            }
        });
    }

    private void fillData(){
        fillBanner();
        username.setText(userDetail.userInfo.nickname + "，" + Utils.getAge(userDetail.userInfo.birthday));
        if(!TextUtils.isEmpty(userDetail.userInfo.femaleType))
            username.setCompoundDrawablesWithIntrinsicBounds(0, 0, Utils.getShengyouTypeImage(userDetail.userInfo.femaleType), 0);
        desc.setText(userDetail.userInfo.description);
        follow.setText("" + userDetail.favCount);
        follower.setText("" + userDetail.fansCount);
        if(userDetail.actress) {
            attractiveness.setText("" + userDetail.user.attractiveness);
            attraTxt.setText("魅惑值");
        }
        else {
            attraTxt.setText("土豪值");
            attractiveness.setText("" + userDetail.user.contribution);
        }

        if(userDetail.giftMap != null && userDetail.giftMap.size() > 0){
            ArrayList<String> ids = new ArrayList<>();
            Set<Map.Entry<String, Integer>> set = userDetail.giftMap.entrySet();
            Iterator<Map.Entry<String, Integer>> ite = set.iterator();
            while(ite.hasNext()){
                Map.Entry<String, Integer> entry = ite.next();
                if(entry.getValue() == 0)
                    continue;
                ids.add(entry.getKey());
            }
            UserDetailGiftAdapter giftAdapter = new UserDetailGiftAdapter();
            giftAdapter.setGifts(userDetail.giftMap);
            giftAdapter.setGiftList(userDetail.giftList);
            mygifts.setLayoutManager(new StaggeredGridLayoutManager(2,
                    StaggeredGridLayoutManager.HORIZONTAL));
            mygifts.setAdapter(giftAdapter);
            giftAdapter.setNewData(ids);
            giftAdapter.notifyDataSetChanged();
        } else {
            gifts_layout.setVisibility(View.GONE);
        }
        if(userDetail.contributionList != null && userDetail.contributionList.size() > 0){
            RankAdapter rankAdapter = new RankAdapter(userDetail.contributionList, 2);
            rankAdapter.notNeedTop();
            rankAdapter.setUserInfoList(userDetail.contributionUserInfoList);
            myshouhu.setLayoutManager(new LinearLayoutManager(this));
            myshouhu.setAdapter(rankAdapter);
            rankAdapter.notifyDataSetChanged();
        } else {
            shouhu_layout.setVisibility(View.GONE);
        }
        if(userDetail.actress && userDetail.user.id != getLoginResponse().user.id) {
            dianhua.setVisibility(View.VISIBLE);
            dianhua.setText(userDetail.userInfo.costPerMin + "豆/分钟");
        } else {
            dianhua.setVisibility(View.GONE);
        }
        if(userDetail.fav) {
            guanzhu.setText("已关注");
            guanzhu.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.btn_forrow), null, null);
        } else {
            guanzhu.setText("关注");
            guanzhu.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.btn_unforrow), null, null);
        }
    }

    @Override
    public int getContentView() {
        return R.layout.activity_user_info;
    }

    private void fillBanner() {
        if(userDetail.userInfo.imageList == null || userDetail.userInfo.imageList.size() == 0)
            return;
        List<String> imageList = new ArrayList<>();
        for(String image : userDetail.userInfo.imageList){
            imageList.add(Utils.getImageUrl(this, image));
        }
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setImageLoader(new GlideImageLoader());
        banner.setImages(imageList);
        banner.setBannerAnimation(Transformer.Default);
        banner.isAutoPlay(true);
        banner.setDelayTime(5000);
        banner.start();
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
            }
        });
    }

    @OnClick({R.id.gift, R.id.dianhua, R.id.guanzhu,
            R.id.sound, R.id.expand, R.id.followLayout, R.id.followerLayout, R.id.arrtractivenessLayout})
    public void onViewClicked(View view) {
        if(userDetail == null)
            return;
        switch (view.getId()) {
            case R.id.gift:
                showSendGiftsDialog(userDetail.user.id, userDetail.card.getTotalAmount(), new SendGiftsDialog.OnSendListener() {
                    @Override
                    public void onSendGifts(List<GiftEntity> gifts) {
                        List<GiveGiftListItem> list = new ArrayList<>();
                        for(int i = 0; i < gifts.size(); i++){
                            list.add(new GiveGiftListItem(gifts.get(i).getId(), gifts.get(i).count));
                        }
                        Api.getInstance().giveGifts(userDetail.user.id, new Gson().toJson(list), new BaofangCallback<String>() {
                            @Override
                            public void onFailure(Call call, Throwable t) {

                            }

                            @Override
                            public void onSuccess(String o) {
                                toast("赠送成功");
                            }
                        });
                    }
                });
                break;
            case R.id.dianhua:
                if(!Utils.isLogin()){
                    startActivity(LoginRegActivity.class);
                    return;
                }
                int yue = userDetail.card.getTotalAmount();
                int candyPerMin = userInfo.costPerMin;
                if(candyPerMin == 0){
                    candyPerMin = 10;
                }
                int remain = yue / candyPerMin;
                if(remain == 0){
                    showYesOrNoDialog("您的余额不够支付一分钟通话资费", "取消", "充值", new YesOrNoDialog.OnClickListener() {
                        @Override
                        public void onLeftClick() {

                        }

                        @Override
                        public void onRightClick() {
                            RechargeActivity.show(UserInfoActivity.this);
                        }
                    });
                    return;
                }
                if(userDetail.room != null){
                    showYesOrNoDialog("主播正在包房直播，无法接听电话，是否进入包房", "取消", "进入", new YesOrNoDialog.OnClickListener() {
                        @Override
                        public void onLeftClick() {

                        }

                        @Override
                        public void onRightClick() {
                            RoomItemResponse roomItemResponse = new RoomItemResponse();
                            roomItemResponse.room = userDetail.room;
                            roomItemResponse.userInfo = userInfo;
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("room", roomItemResponse);
                            startActivity(RoomActivity.class, bundle);
                        }
                    });
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putSerializable("userInfo", userInfo);
                bundle.putString("avatar", userInfo.avatar);
                bundle.putString("nickname", userInfo.nickname);
                startActivity(CalloutActivity.class, bundle);
                break;
            case R.id.guanzhu:
                Api.getInstance().fav(userDetail.user.id, new BaofangCallback() {
                    @Override
                    public void onFailure(Call call, Throwable t) {

                    }

                    @Override
                    public void onSuccess(Object o) {

                    }
                });
                userDetail.fav = !userDetail.fav;
                if(userDetail.fav) {
                    guanzhu.setText("已关注");
                    guanzhu.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.btn_forrow), null, null);
                } else {
                    guanzhu.setText("关注");
                    guanzhu.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.btn_unforrow), null, null);
                }
                break;
            case R.id.sound:
                if(playThread != null && playThread.isAlive())
                    return;
                playThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String path = ACache.get(BaojianApplication.getInstance()).getAsString("imageDomain") + userDetail.userInfo.audioPath;     //这里给一个歌曲的网络地址就行了
                        Uri uri = Uri.parse(path);
                        if(player != null){
                            player.release();//释放资源
                        }
                        player = MediaPlayer.create(UserInfoActivity.this, uri);
                        if(player != null)
                            player.start();
                    }
                });
                playThread.start();
                break;
            case R.id.expand:
                expand.setVisibility(View.GONE);
                expandableContent.setVisibility(View.VISIBLE);
                break;
            case R.id.followLayout: {
                Intent intent = new Intent(this, FollowActivity.class);
                intent.putExtra("userid", userInfo.userId);
                startActivity(intent);
            }
                break;
            case R.id.followerLayout: {
                Intent intent = new Intent(this, FansActivity.class);
                intent.putExtra("userid", userInfo.userId);
                startActivity(intent);
            }
                break;
            case R.id.arrtractivenessLayout:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(player != null) {
            player.stop();
            player.release();
        }
        if(playThread != null){
            playThread = null;
        }
    }
}
